<template>
  <div class="form-demo">
    <h2>表单示例 - 使用自定义MSelect</h2>
    
    <m-form
      ref="formRef"
      :model="formData"
      :items="formItems"
      label-width="120px"
      @change="handleFormChange"
    >
      <template #append>
        <div class="form-buttons">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </template>
    </m-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import MForm from '@/components/MForm.vue'
import MSelect from '@/components/MSelect.vue'

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  name: '',
  age: 0,
  city: '',
  customCity: '',
  multipleCity: []
})

// 城市选项
const cityOptions = [
  { label: '北京', value: 1 },
  { label: '上海', value: 2 },
  { label: '广州', value: 3 },
  { label: '深圳', value: 4 }
]

// 表单项配置
const formItems = [
  {
    label: '姓名',
    prop: 'name',
    type: 'input',
    required: true
  },
  {
    label: '年龄',
    prop: 'age',
    type: 'number',
    required: true
  },
  {
    label: '城市(原生)',
    prop: 'city',
    type: 'select',
    options: cityOptions,
    required: true
  },
  {
    label: '城市(自定义)',
    prop: 'customCity',
    // 使用自定义MSelect组件
    component: MSelect,
    props: {
      options: cityOptions,
      placeholder: '请选择城市',
      width: '100%'
    },
    required: true
  },
  {
    label: '多选城市',
    prop: 'multipleCity',
    // 使用自定义MSelect组件的多选模式
    component: MSelect,
    props: {
      options: cityOptions,
      placeholder: '请选择多个城市',
      width: '100%',
      multiple: true
    }
  }
]

// 表单变化事件处理
const handleFormChange = (prop: string, value: any, formData: any) => {
  console.log('表单项变化:', prop, value, formData)
}

// 提交表单
const submitForm = async () => {
  try {
    const valid = await formRef.value.validate()
    if (valid) {
      console.log('表单提交成功:', formRef.value.formData)
      // 执行提交操作
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<style lang="scss" scoped>
.form-demo {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  
  h2 {
    margin-bottom: 20px;
    color: #303133;
  }
  
  .form-buttons {
    margin-top: 20px;
    text-align: center;
  }
}
</style> 